package com.example.myapplication.LocationTest;
import android.widget.TextView;
import com.baidu.location.BDLocationListener;
import android.widget.Toast;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;

public class MyLocationListener extends BDAbstractLocationListener implements BDLocationListener {
  BaiduMap baiduMap;
  MapView mapView;
  TextView textView;

  public MyLocationListener(BaiduMap baiduMap, MapView mapView, TextView textView) {
    this.baiduMap = baiduMap;
    this.mapView = mapView;
    this.textView = textView;
  }

  public MyLocationListener(BaiduMap baiduMap, TextView textView) {
    this.baiduMap = baiduMap;
    this.textView = textView;
  }

  public MyLocationListener(BaiduMap baiduMap, MapView mapView) {
    this.baiduMap = baiduMap;
    this.mapView = mapView;
  }

  @Override public void onReceiveLocation(BDLocation bdLocation) {
    if (bdLocation == null || baiduMap == null) {
      Toast.makeText(mapView.getContext(), "初始化失败", Toast.LENGTH_SHORT).show();
      return;
    }
    //获取定位结果
    double latitude = bdLocation.getLatitude();//纬度
    double longitude = bdLocation.getLongitude();//经度
    //构建定位数据
    MyLocationData locationData = new MyLocationData.Builder()
        .accuracy(bdLocation.getRadius())//定位精度
        .direction(bdLocation.getDirection())//GPS定位时方向角度
        .latitude(latitude)
        .longitude(longitude)
        .build();
    //设置定位数据
    baiduMap.setMyLocationData(locationData);
    //移动地图到定位点
    LatLng latLng = new LatLng(latitude, longitude);
    System.out.println("当前经度" + latitude);
    System.out.println("当前方向"+locationData.direction);
    baiduMap.setMapStatus(com.baidu.mapapi.map.MapStatusUpdateFactory.newLatLng(latLng));
    float radius = bdLocation.getRadius();    //获取定位精度，默认值为0.0f
    int errorCode = bdLocation.getLocType();            //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明
    String coorType = bdLocation.getCoorType();
    String  s1="纬度:"+String.valueOf(latitude);
    String  s2="经度:"+String.valueOf(longitude);
    String s3="定位精度:"+String.valueOf(radius);
    if (textView != null) {
      textView.setText("\n\n" + s1+"\n"+s2+"\n"+s3+"\n"+"详细地址:"+bdLocation.getAddrStr()+"\n"
          +"国家:"+bdLocation.getCountry()+"\n"+"省份:"+bdLocation.getProvince()+"\n城市:"+bdLocation.getCity()
          +"\n区县:"+bdLocation.getDistrict()
          +"\n街道信息:"+bdLocation.getStreet()+"\n返回码："+errorCode+"\n坐标类型:"+coorType+"\n返回值类型"+bdLocation.getLocType());
    }

    Toast.makeText(mapView.getContext(), "定位成功", Toast.LENGTH_SHORT).show();

  }


}
